﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.CurriculoPack
{
    [Serializable()]
    public class Experiencia : BusinessBase<Experiencia>
    {
        #region Control Properties
        [Csla.NotUndoable()]
        private bool _isEmpty = false;

        public bool IsEmpty
        {
            get { return _isEmpty; }
        }
        #endregion

        #region Business Properties and Methods

        //declare members

        private Guid _id = Guid.NewGuid();

        private Guid _idCurriculo = Guid.NewGuid();

        private Guid _idAreaAtuacao = Guid.NewGuid();
        
        private String _empresa = String.Empty;

        private String _cargo = String.Empty;
       
        private String _descricao = String.Empty;

        private DateTime _dataInicio = DateTime.Now;
        
        private DateTime _dataFim = DateTime.Now;


        [System.ComponentModel.DataObjectField(true, true)]
        public Guid Id
        {
            get
            {
                CanReadProperty("Id", true);
                return _id;
            }
        }

        public Guid IdCurriculo
        {
            get
            {
                CanReadProperty("IdCurriculo", true);
                return _idCurriculo;
            }
            set
            {
                CanWriteProperty("IdCurriculo", true);
                if (value == null) value = Guid.NewGuid();
                if (!_idCurriculo.Equals(value))
                {
                    _idCurriculo = value;
                    PropertyHasChanged("IdCurriculo");
                }
            }
        }

        public Guid IdAreaAtuacao
        {
            get
            {
                CanReadProperty("IdAreaAtuacao", true);
                return _idAreaAtuacao;
            }
            set
            {
                CanWriteProperty("IdAreaAtuacao", true);
                if (value == null) value = Guid.NewGuid();
                if (!_idAreaAtuacao.Equals(value))
                {
                    _idAreaAtuacao = value;
                    PropertyHasChanged("IdAreaAtuacao");
                }
            }
        }

        public String Empresa
        {
            get
            {
                CanReadProperty("Empresa", true);
                return _empresa;
            }
            set
            {
                CanWriteProperty("Empresa", true);
                if (value == null) value = String.Empty;
                if (!_empresa.Equals(value))
                {
                    _empresa = value;
                    PropertyHasChanged("Empresa");
                }
            }
        }

        public String Cargo
        {
            get
            {
                CanReadProperty("Cargo", true);
                return _cargo;
            }
            set
            {
                CanWriteProperty("Cargo", true);
                if (value == null) value = String.Empty;
                if (!_cargo.Equals(value))
                {
                    _cargo = value;
                    PropertyHasChanged("Cargo");
                }
            }
        }

        public String Descricao
        {
            get
            {
                CanReadProperty("Descricao", true);
                return _descricao;
            }
            set
            {
                CanWriteProperty("Descricao", true);
                if (value == null) value = String.Empty;
                if (!_descricao.Equals(value))
                {
                    _descricao = value;
                    PropertyHasChanged("Descricao");
                }
            }
        }

        public DateTime DataInicio
        {
            get
            {
                CanReadProperty("DataInicio", true);
                return _dataInicio;
            }
            set
            {
                CanWriteProperty("DataInicio", true);
                if (value == null) value = DateTime.Now;
                if (!_dataInicio.Equals(value))
                {
                    _dataInicio = value;
                    PropertyHasChanged("DataInicio");
                }
            }
        }

        public DateTime DataFim
        {
            get
            {
                CanReadProperty("DataFim", true);
                return _dataFim;
            }
            set
            {
                CanWriteProperty("DataFim", true);
                if (value == null) value = DateTime.Now;
                if (!_dataFim.Equals(value))
                {
                    _dataFim = value;
                    PropertyHasChanged("DataFim");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id.ToString();
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in Experiencia
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in Experiencia
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ExperienciaViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in Experiencia
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ExperienciaAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in Experiencia
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ExperienciaEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in Experiencia
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("ExperienciaDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Experiencia()
        { /* require use of factory method */ }

        public static Experiencia NewExperiencia()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Experiencia");
            return DataPortal.Create<Experiencia>();
        }

        public static Experiencia GetExperiencia(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("Usuário não autorizado a visualizar Experiencia");
            return DataPortal.Fetch<Experiencia>(new Criteria(id));
        }

        public override Experiencia Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Experiencia");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("Usuário não autorizado a adicionar Experiencia");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("Usuário não autorizado a atualizar Experiencia");

            return base.Save();
        }

        public static void DeleteExperiencia(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("Usuário não autorizado a remover Experiencia");
            DataPortal.Delete(new Criteria(id));
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Id;

            public Criteria(Guid Id)
            {
                this.Id = Id;

            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            _isEmpty = false;
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteFetch(cn, criteria);
            }//using

        }

        private void ExecuteFetch(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetFetchScript(criteria);

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    FetchObject(dr);
                    ValidationRules.CheckRules();

                    //load child object(s)
                    FetchChildren(dr);
                }
            }//using
        }

        private String GetFetchScript(Criteria criteria)
        {
            return "SELECT Id, IdCurriculo, IdAreaAtuacao, Empresa, DataInicio, DataFim, Cargo, Descricao "
                 + "FROM experienciatb WHERE Id=\"" + criteria.Id.ToString() + "\";";
        }

        private void FetchObject(SafeDataReader dr)
        {
            _isEmpty = !dr.Read();
            if (_isEmpty) return;

            _id = new Guid(dr["Id"].ToString());
            _idCurriculo = new Guid(dr["IdCurriculo"].ToString());
            _idAreaAtuacao = new Guid(dr["IdAreaAtuacao"].ToString());
            _cargo = dr.GetString("Cargo");
            _descricao = dr.GetString("Descricao");
            _dataInicio = dr.GetDateTime("DataInicio");
            _empresa = dr.GetString("Empresa");
            _dataFim = dr.GetDateTime("DataFim");

        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteInsert(cn);

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Insert - experienciatb - Id: " + _id.ToString());
        }

        private void ExecuteInsert(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetInsertScript();

                cm.ExecuteNonQuery();



            }//using
        }

        private String GetInsertScript()
        {
            return "INSERT INTO experienciatb(Id, IdCurriculo, IdAreaAtuacao, Empresa, Cargo, Descricao, DataInicio, DataFim ) VALUES (\""
                + _id.ToString() + "\", \""
                + _idCurriculo.ToString() + "\", \""
                + _idAreaAtuacao.ToString() + "\", \""
                + _empresa.ToString() + "\", \""
                + _cargo.ToString() + "\", \""
                + _descricao.ToString() + "\", \""
                + _dataInicio.ToString("yyyy-MM-dd HH:mm:ss") + "\", \""
                + _dataFim.ToString("yyyy-MM-dd HH:mm:ss") + "\")";
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                if (base.IsDirty)
                {
                    ExecuteUpdate(cn);
                }

                //update child object(s)
                UpdateChildren(cn);
            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Update - experienciatb - Id: " + _id.ToString());
        }

        private void ExecuteUpdate(OdbcConnection cn)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = GetUpdateScript();

                if (cm.ExecuteNonQuery() == 0)
                    throw new Exception("Este registro foi editado por outro usuario.");
            }//using
        }

        private String GetUpdateScript()
        {
            return "Update experienciatb set "
                    + "IdCurriculo=\"" + _idCurriculo.ToString() + "\", "
                    + "IdAreaAtuacao=\"" + _idAreaAtuacao.ToString() + "\", "
                    + "Empresa=\"" + _empresa.ToString() + "\", "
                    + "Cargo=\"" + _cargo.ToString() + "\", "
                    + "Descricao=\"" + _descricao.ToString() + "\", "
                    + "DataInicio=\"" + _dataInicio.ToString("yyyy-MM-dd HH:mm:ss") + "\", "
                    + "DataFim=\"" + _dataFim.ToString("yyyy-MM-dd HH:mm:ss") + "\" "
                    + "WHERE Id=\"" + _id.ToString() + "\";";
        }

        private void UpdateChildren(OdbcConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            {
                cn.Open();

                ExecuteDelete(cn, criteria);

            }//using
            MinaspetroLibrary.UsuarioPack.Usuario.UsuarioInSession.AtualizarHitorico("Delete - experienciatb - Id: " + _id.ToString());
        }

        private void ExecuteDelete(OdbcConnection cn, Criteria criteria)
        {
            using (OdbcCommand cm = cn.CreateCommand())
            {
                cm.CommandType = CommandType.Text;
                cm.CommandText = cm.CommandText = "DELETE from experienciatb WHERE IdCurriculo=\"" + criteria.Id.ToString() + "\";";

                cm.ExecuteNonQuery();
            }//using
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
